package com.hup.utils.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;

import java.util.HashMap;

/**
 * 使用缓存方法,处理findElement的耗时过长问题,解决某些业务[执行对时长敏感]的问题
 * 每次findElement都要耗时20ms
 *  每个页面20个对象,耗时400ms
 *      5个页面,总耗时2秒
 * 隐患:
 * 缓存元素与实际不匹配时
 *  新页签/新句柄时:会报错
 *  页签句柄无变化,但元素被替换,id等识别符没变:暂时没遇到
 * @author hugan
 * @date 2020/3/26
 */
public class ElementCacher {

    private HashMap<String, WebElement> map = new HashMap<>();

    /**
     * 用于如:页签被关闭后重启了,就要清理缓存
     */
    public void cleanCache() {
        map.clear();
    }

    public WebElement findElement(String name, SearchContext searchContext, By... bys) {
        return map.computeIfAbsent(name, k -> ElementUtil.findElement(searchContext, bys));
    }

    public Double getDoubleAllowErr(String name, SearchContext searchContext, By... bys) {
        WebElement element = map.computeIfAbsent(name, k -> ElementUtil.findElement(searchContext, bys));
        return ElementUtil.getDoubleAllowErr(element);
    }

    public Integer getIntegerAllowErr(String name, SearchContext searchContext, By... bys) {
        WebElement element = map.computeIfAbsent(name, k -> ElementUtil.findElement(searchContext, bys));
        return ElementUtil.getIntegerAllowErr(element);
    }

}
